const md5 = require("js-md5");
const tokenMiddleware = require("../../middleware/token.Middleware");
const resultFormatMiddleware = require('../../middleware/resultFormat.Middleware')
const authController = require('../../controller/auth.controller')

class AuthRouter {

    constructor(router) {
        router.post('/sign', async function (req, res) {
            // 在express中 接收参数在req中 其中 body 对应post请求中的参数 ， query 对应 get请求中的参数， params 对应 路径参数 /:id
            let {username, password} = req.body ? req.body : void 0

            if (!username) return await resultFormatMiddleware.fail(res, '请输入用户名')
            if (!password) return await resultFormatMiddleware.fail(res, '请输入密码')
            let [raw, f] = await authController.findUserByName(username)
            if (raw.length === 0) return await resultFormatMiddleware.fail(res, '用户名不存在')
            //the password  algorithm is password generate string call md5() after call md5() so password str = md5(md5(password)).
            let _password = md5(md5(password))
            if (_password === '14e1b600b1fd579f47433b88e8d85291') {
                delete raw[0].password
                let token = req.session.token = tokenMiddleware.sign(raw[0])
                await resultFormatMiddleware.success(res, `签发成功 ${token}`, 200, [raw])
            } else return await resultFormatMiddleware.fail(res, '密码不正确', 500, [])
        })

        router.post('/verify', tokenMiddleware.verifyMiddleware, function (req, res) {
            let arr = [req.user, req.headers]
            if (req.user && Object.keys(req.user).length > 0) {
                return resultFormatMiddleware.success(res, undefined, 200, arr)
            } else {
                return resultFormatMiddleware.fail(res, undefined, 500, arr)
            }
        })
    }
}

module.exports = AuthRouter

